package com.haoshuang.zhouzhoubang.ui.page.settled.settled

import android.Manifest
import android.content.Context
import android.location.Location
import android.os.Bundle
import androidx.core.widget.addTextChangedListener
import com.blankj.utilcode.util.SizeUtils
import com.haoshuang.zhouzhoubang.MyApp
import com.haoshuang.zhouzhoubang.R
import com.haoshuang.zhouzhoubang.config.URLConstants
import com.haoshuang.zhouzhoubang.databinding.ActivityStoreSettledInputBinding
import com.haoshuang.zhouzhoubang.model.bean.CooperationTimeBean
import com.haoshuang.zhouzhoubang.model.bean.IDCardBean
import com.haoshuang.zhouzhoubang.model.bean.SettledInfoBean
import com.haoshuang.zhouzhoubang.model.event.RefreshHomeData
import com.haoshuang.zhouzhoubang.ui.dialog.ConfirmDialog
import com.haoshuang.zhouzhoubang.ui.dialog.HelpDescriptionDialog
import com.haoshuang.zhouzhoubang.ui.dialog.ShowUploadExampleDialog
import com.haoshuang.zhouzhoubang.ui.dialog.UploadExample
import com.haoshuang.zhouzhoubang.ui.page.help.detail.HelpDetailActivity
import com.haoshuang.zhouzhoubang.ui.page.settled.contactbutler.ContactButlerActivity
import com.haoshuang.zhouzhoubang.utils.LocationUtils
import com.haoshuang.zhouzhoubang.utils.MultiMediaChooseUtils
import com.haoshuang.zhouzhoubang.utils.OSSUploadUtils
import com.haoshuang.zhouzhoubang.utils.PermissionHelper
import com.haoshuang.zhouzhoubang.widget.CustomUploadView
import com.haoshuang.zhouzhoubang.widget.UploadFileBean
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupPosition
import com.mufeng.libs.base.BaseVMActivity
import com.mufeng.libs.state.observeState
import com.mufeng.libs.utils.ktx.convertInt
import com.mufeng.libs.utils.ktx.runOnUIThread
import com.mufeng.libs.utils.startPage
import com.mufeng.libs.utils.toast
import com.mufeng.libs.utils.view.click
import com.mufeng.libs.utils.view.clickWithTrigger
import com.mufeng.libs.utils.view.gone
import com.mufeng.libs.utils.view.load
import com.mufeng.libs.utils.view.visible
import com.mufeng.libs.utils.view.visibleOrGone


/**
 *  门店入驻
 */
class StoreSettledInputActivity :
    BaseVMActivity<StoreSettledInputViewModel, ActivityStoreSettledInputBinding>() {

    /**
     * 入驻信息实体
     */
    private var settledInfo: SettledInfoBean? = SettledInfoBean()

    // 合作期限列表
    private val cooperationTimeList = arrayListOf<CooperationTimeBean>()

    private var lat = ""
    private var lng = ""

    // 是否编辑 0不编辑
    private var isEdit = 0

    // 身份证识别信息
    private var idCardBean: IDCardBean? = null

    companion object {
        fun launch(context: Context) {
            context.startPage<StoreSettledInputActivity>()
        }
    }

    override fun initView(savedInstanceState: Bundle?) {

        binding.titleBar.title = "门店入驻"
        binding.titleBar.leftImageView().click { finish() }

        // 联系管家
        binding.tvContactButler.click {
            startPage<ContactButlerActivity>()
        }

        binding.etName.addTextChangedListener {
            settledInfo?.real_name = it.toString()
        }

        binding.etPhone.addTextChangedListener {
            settledInfo?.mobile = it.toString()
        }

        // 身份证正面
        binding.rivUploadIDCardFront.setOnUploadResultListener(object : CustomUploadView.OnUploadResultListener{
            override fun onUploadResult(mediaList: List<UploadFileBean>) {
                settledInfo?.card_front = mediaList[0].url
                if (settledInfo?.card_front?.isNotEmpty() == true && settledInfo?.card_side?.isNotEmpty() == true){
                    vm.idCardRecognition(settledInfo?.card_front?:"", settledInfo?.card_side?:"")
                }
            }
        })

        // 身份证反面上传
        binding.rivUploadIDCardBack.setOnUploadResultListener(object : CustomUploadView.OnUploadResultListener{
            override fun onUploadResult(mediaList: List<UploadFileBean>) {
                settledInfo?.card_side = mediaList[0].url
                if (settledInfo?.card_front?.isNotEmpty() == true && settledInfo?.card_side?.isNotEmpty() == true){
                    vm.idCardRecognition(settledInfo?.card_front?:"", settledInfo?.card_side?:"")
                }
            }
        })

        // 门店名称
        binding.etStoreName.addTextChangedListener {
            settledInfo?.team_name = it.toString()
        }

        binding.tvChooseEntity.clickWithTrigger {
            XPopup.Builder(mActivity)
                .asBottomList(
                    "是否有实体门店",
                    arrayOf("没有实体店", "有实体店")
                ) { position, text ->
                    settledInfo?.is_entity = position
                    binding.tvChooseEntity.text = text
                    binding.llTeamLogo.visibleOrGone(position == 1)
                }
                .show()
        }


        // 门店头像上传
        binding.rivUploadTeamHeadFront.setOnUploadResultListener(object : CustomUploadView.OnUploadResultListener{
            override fun onUploadResult(mediaList: List<UploadFileBean>) {
                settledInfo?.team_logo = mediaList[0].url
            }
        })

        // 门店头像右侧面上传
        binding.rivUploadTeamHeadRight.setOnUploadResultListener(object : CustomUploadView.OnUploadResultListener{
            override fun onUploadResult(mediaList: List<UploadFileBean>) {
                settledInfo?.team_right_logo = mediaList[0].url
            }
        })

        // 门店头像侧面上传
        binding.rivUploadTeamHeadLeft.setOnUploadResultListener(object : CustomUploadView.OnUploadResultListener{
            override fun onUploadResult(mediaList: List<UploadFileBean>) {
                settledInfo?.team_side_logo = mediaList[0].url
            }
        })

        // 门店地址
        binding.tvStoreAddress.clickWithTrigger {
            PermissionHelper.requestPermission(
                mActivity,
                "权限使用说明",
                "获取当前位置进行门店入驻",
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION
            ) {
                if (it) {
                    LocationUtils.register(mActivity, 0, 0, object :
                        LocationUtils.OnLocationChangeListener {
                        override fun getLastKnownLocation(location: Location?) {

                        }

                        override fun onLocationChanged(location: Location?) {
                            lat = location?.latitude.toString()
                            lng = location?.longitude.toString()
                            MyApp.lat = lat
                            MyApp.lng = lng
                            LocationUtils.unregister()
                            vm.getRemoteAddress(lat, lng)
                        }

                        override fun onStatusChanged(
                            provider: String?,
                            status: Int,
                            extras: Bundle?
                        ) {

                        }
                    })
                } else {
                    toast("请开启定位权限")
                }
            }
        }

        // 门店现有人数
        binding.etStoreMemberNum.addTextChangedListener {
            settledInfo?.team_num = it.toString().convertInt()
        }

        // 营业执照
        binding.rivBusinessLicense.setOnUploadResultListener(object : CustomUploadView.OnUploadResultListener{
            override fun onUploadResult(mediaList: List<UploadFileBean>) {
                settledInfo?.team_company_pic = mediaList[0].url
            }
        })

        // 门店介绍
        binding.etStoreIntroduction.addTextChangedListener {
            settledInfo?.synopsis = it.toString()
        }

        // 选择合作期限
        binding.llCooperationTime.clickWithTrigger {
            if (settledInfo?.city.isNullOrEmpty()) {
                toast("请选择门店地址")
                return@clickWithTrigger
            }
            vm.getCooperationPeriod(settledInfo?.city)
        }

        binding.ivStoreHeadPicHelp.click {
            XPopup.Builder(mActivity)
                .popupPosition(PopupPosition.Right)
                .animationDuration(0)
                .borderRadius(SizeUtils.dp2px(10f).toFloat())
                .hasShadowBg(false)
                .atView(binding.ivStoreHeadPicHelp)
                .asCustom(HelpDescriptionDialog(mActivity, "门店头像请上传规范清晰真实的门头照片"))
                .show()
        }

        binding.ivBusinessLicenseHelp.click {
            XPopup.Builder(mActivity)
                .popupPosition(PopupPosition.Right)
                .animationDuration(0)
                .borderRadius(SizeUtils.dp2px(10f).toFloat())
                .hasShadowBg(false)
                .atView(binding.ivBusinessLicenseHelp)
                .asCustom(
                    HelpDescriptionDialog(
                        mActivity,
                        "营业执照入驻时可不必填，入驻后需将在${MyApp.systemConfig?.company_pic_day}天内补齐 否则将影响订单推送。"
                    )
                )
                .show()
        }

        binding.tvApply.clickWithTrigger {
            XPopup.Builder(mActivity)
                .asCustom(
                    ConfirmDialog(
                        context = mActivity,
                        title = "温馨提示",
                        content = "入驻申请资料已提交, 系统将在\n1~3工作日进行联系审核",
                        cancelStr = "",
                        confirmStr = "我知道了",
                        isHideCancel = true,
                        onCancel = {},
                        onConfirm = {})
                )
                .show()
        }

        binding.tvCooperationPolicies.clickWithTrigger {
            // 查看合作政策
            startPage<HelpDetailActivity>(
                "title" to "合作政策",
                "url" to "${URLConstants.baseUrl}index/help/helpInfo?id=30"
            )
        }

        binding.tvLookIDCardSample.clickWithTrigger {
            // 身份证上传查看示例
            XPopup.Builder(mActivity)
                .asCustom(ShowUploadExampleDialog(context =mActivity, order_id = "", type = 4, localList = mutableListOf(
                    UploadExample("身份证正面", R.mipmap.icon_id_card_upload_sample),
                    UploadExample("身份证反面", R.mipmap.icon_id_card_side_upload_sample),
                )))
                .show()
        }

        binding.tvLookBusinessLicenseSample.clickWithTrigger {
            // 营业执照上传查看示例
            XPopup.Builder(mActivity)
                .asCustom(ShowUploadExampleDialog(context =mActivity, order_id = "", type = 4, localList = mutableListOf(
                    UploadExample("营业执照", R.mipmap.icon_team_business_license_upload_sample),
                )))
                .show()
        }

        binding.tvLookTeamHeadSample.clickWithTrigger {
            // 门头上传查看示例
            XPopup.Builder(mActivity)
                .asCustom(ShowUploadExampleDialog(context =mActivity, order_id = "", type = 4, localList = mutableListOf(
                    UploadExample("门头正面", R.mipmap.icon_team_logo_upload_sample),
                    UploadExample("门头左侧面", R.mipmap.icon_team_side_logo_upload_sample),
                    UploadExample("门头右侧面", R.mipmap.icon_team_upload_right_sample),
                )))
                .show()
        }

        binding.tvApply.clickWithTrigger {
            // 提交申请
            // 判断是否填写完整
            if (settledInfo?.real_name.isNullOrEmpty()) {
                toast("请填写姓名")
                return@clickWithTrigger
            }
            if (settledInfo?.mobile.isNullOrEmpty()) {
                toast("请填写手机号")
                return@clickWithTrigger
            }
            if (settledInfo?.mobile?.length != 11 || !settledInfo?.mobile?.startsWith("1")!!){
                toast("请输入有效手机号")
                return@clickWithTrigger
            }
            if (settledInfo?.card_front.isNullOrEmpty() || settledInfo?.card_side.isNullOrEmpty()) {
                toast("请上传身份证")
                return@clickWithTrigger
            }
            if (idCardBean == null){
                toast("身份证识别失败, 请重新上传")
                return@clickWithTrigger
            }
            if (binding.etRealName.text.toString().isEmpty()){
                toast("请输入身份证的真实姓名")
                return@clickWithTrigger
            }
            if (binding.etIDCardNumber.text.toString().isEmpty()){
                toast("请输入身份证的证件号码")
                return@clickWithTrigger
            }
            if (settledInfo?.team_name.isNullOrEmpty()) {
                toast("请填写门店名称")
                return@clickWithTrigger
            }
            if (settledInfo?.is_entity == 1) {
                if (settledInfo?.team_logo.isNullOrEmpty() || settledInfo?.team_side_logo.isNullOrEmpty() || settledInfo?.team_right_logo.isNullOrEmpty()) {
                    toast("请上传门店照片")
                    return@clickWithTrigger
                }
            }
            if (settledInfo?.province.isNullOrEmpty() || settledInfo?.city.isNullOrEmpty() || settledInfo?.area.isNullOrEmpty() || settledInfo?.address.isNullOrEmpty()) {
                toast("请选择门店所在地区")
                return@clickWithTrigger
            }
            if (settledInfo?.service_year == null || settledInfo?.service_year == 0) {
                toast("请选择合作期限")
                return@clickWithTrigger
            }

            if (settledInfo?.team_company_pic.isNullOrEmpty()) {
                XPopup.Builder(mActivity)
                    .asCustom(
                        ConfirmDialog(
                            context = mActivity,
                            title = "温馨提示",
                            content = "营业执照入驻时可不必填，入驻后需将在${MyApp.systemConfig?.company_pic_day}天内补齐 否则将影响订单推送。",
                            cancelStr = "返回上传",
                            confirmStr = "继续提交",
                            isHideCancel = true,
                            onCancel = {},
                            onConfirm = {
                                XPopup.Builder(mActivity)
                                    .asCustom(ConfirmDialog(
                                        context =mActivity,
                                        title = "温馨提示",
                                        content = "申请入驻时, 请确认身份证识别出的真实姓名和身份证号无误后, 再提交",
                                        cancelStr = "返回修改",
                                        confirmStr = "确认提交",
                                        isHideCancel = false,
                                        isHideAgain = false,
                                        onCancel = {},
                                        onConfirm = {
                                            vm.applySettled(settledInfo, isEdit,idCardBean?.face?.Address,
                                                idCardBean?.face?.BirthDate,
                                                idCardBean?.back?.EndDate,
                                                idCardBean?.face?.Gender,
                                                binding.etIDCardNumber.text.toString(),
                                                idCardBean?.back?.Issue,
                                                binding.etRealName.text.toString(),
                                                idCardBean?.face?.Nationality,
                                                idCardBean?.back?.StartDate)
                                        }))
                                    .show()
                            })
                    )
                    .show()
                return@clickWithTrigger
            }else{
                XPopup.Builder(mActivity)
                    .asCustom(ConfirmDialog(
                        context =mActivity,
                        title = "温馨提示",
                        content = "申请入驻时, 请确认身份证识别出的真实姓名和身份证号无误后, 再提交",
                        cancelStr = "返回修改",
                        confirmStr = "确认提交",
                        isHideCancel = false,
                        isHideAgain = false,
                        onCancel = {},
                        onConfirm = {
                            vm.applySettled(settledInfo, isEdit,idCardBean?.face?.Address,
                                idCardBean?.face?.BirthDate,
                                idCardBean?.back?.EndDate,
                                idCardBean?.face?.Gender,
                                binding.etIDCardNumber.text.toString(),
                                idCardBean?.back?.Issue,
                                binding.etRealName.text.toString(),
                                idCardBean?.face?.Nationality,
                                idCardBean?.back?.StartDate)
                        }))
                    .show()
            }

        }

    }

    override fun initData() {
        vm.getStoreSettledInfo()
    }

    override fun startObserve() {

        vm.getRemoteAddressData.observeState(this){
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                val address = it?.data?.regeocodes?.firstOrNull()?.addressComponent

                val province = address?.province.toString()
                val city = address?.city.toString()
                val area = address?.district.toString()
                val street = address?.streetNumber?.street.toString()
                val streetNumber = address?.streetNumber?.number.toString()
                binding.tvStoreAddress.text =
                    "${province}${city}${area}${street}${streetNumber}"
                settledInfo?.province = province
                settledInfo?.city = city
                settledInfo?.area = area
                settledInfo?.address = "${street}${streetNumber}"
                settledInfo?.lat = lat
                settledInfo?.lng = lng
            }
        }

        vm.applySettledData.observeState(this) {
            onLoading {
                showLoading()
            }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                XPopup.Builder(mActivity)
                    .dismissOnBackPressed(false)
                    .dismissOnTouchOutside(false)
                    .asCustom(
                        ConfirmDialog(
                            context = mActivity,
                            title = "温馨提示",
                            content = "入驻申请资料已提交, 系统将在\n1-3个工作日进行联系审核",
                            cancelStr = "",
                            confirmStr = "我知道了",
                            isHideCancel = true,
                            onCancel = {},
                            onConfirm = {
                                LiveEventBus.get(RefreshHomeData::class.java).post(RefreshHomeData)
                                finish()
                            })
                    ).show()
            }
        }

        vm.getCooperationPeriodData.observeState(this) {
            onSuccess {
                cooperationTimeList.clear()
                cooperationTimeList.addAll(it?.data ?: mutableListOf())
                if (cooperationTimeList.isNotEmpty()) {
                    XPopup.Builder(mActivity)
                        .asBottomList(
                            "选择合作期限",
                            cooperationTimeList.map {
                                "${it.exp} - ${it.join_year}年${if (it.is_pay_team_money == 0) "" else "/${it.join_money}元"}"
                            }.toTypedArray()
                        ) { position, text ->
                            binding.tvCooperationTime.text = text
                            settledInfo?.service_year = cooperationTimeList[position].join_year
                            settledInfo?.service_id = cooperationTimeList[position].id
                        }
                        .show()
                }
            }
        }

        vm.getStoreSettledInfoData.observeState(this) {
            onSuccess {
                if(it?.data != null){
                    isEdit = 1
                    settledInfo = it?.data
                    setupData(it?.data)
                }else{
                    isEdit = 0
                }
            }
        }

        vm.idCardRecognitionData.observeState(this){
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
                binding.llRealName.gone()
                binding.llIDCardNumber.gone()
                binding.etRealName.setText("")
                binding.etIDCardNumber.setText("")
            }
            onSuccess {
                dismissLoading()
                idCardBean = it
                if (it != null) {
                    binding.llRealName.visible()
                    binding.llIDCardNumber.visible()
                    binding.etRealName.setText(it.face?.Name)
                    binding.etIDCardNumber.setText(it.face?.IDNumber)
                }else{
                    binding.llRealName.gone()
                    binding.llIDCardNumber.gone()
                    binding.etRealName.setText("")
                    binding.etIDCardNumber.setText("")
                }
            }
        }
    }

    /**
     * 设置入驻信息
     */
    private fun setupData(data: SettledInfoBean?) {
        val settledInfo = data
        if (settledInfo != null) {
            // 拒绝原因  布局
            binding.llRejectReason.visibleOrGone(settledInfo!!.status == "2")
            binding.tvRejectReason.text = settledInfo!!.fail_msg

            // 姓名
            binding.etName.setText(settledInfo!!.real_name)
            // 手机号
            binding.etPhone.setText(settledInfo!!.mobile)
            // 身份证正面
            binding.rivUploadIDCardFront.setSingleMedia(settledInfo!!.card_front)
            // 身份证反面
            binding.rivUploadIDCardBack.setSingleMedia(settledInfo!!.card_side)
            vm.idCardRecognition(settledInfo!!.card_front?:"", settledInfo!!.card_side?:"")
            // 门店名称
            binding.etStoreName.setText(settledInfo!!.team_name)
            binding.tvChooseEntity.text = if (settledInfo.is_entity == 1) "有实体店" else "没有实体店"
            binding.llTeamLogo.visibleOrGone(settledInfo.is_entity == 1)
            // 门店头像
            binding.rivUploadTeamHeadFront.setSingleMedia(settledInfo!!.team_logo)
            // 门店头像侧面
            binding.rivUploadTeamHeadRight.setSingleMedia(settledInfo!!.team_right_logo)
            binding.rivUploadTeamHeadLeft.setSingleMedia(settledInfo!!.team_side_logo)
            // 门店地址
            binding.tvStoreAddress.text =
                "${settledInfo!!.province}${settledInfo!!.city}${settledInfo!!.area}${settledInfo!!.address}"
            // 门店人数
            binding.etStoreMemberNum.setText(settledInfo!!.team_num.toString())
            // 营业执照
            binding.rivBusinessLicense.setSingleMedia(settledInfo!!.team_company_pic)
            // 门店简介
            binding.etStoreIntroduction.setText(settledInfo!!.synopsis)
            // 合作期限
            binding.tvCooperationTime.text = "${if (settledInfo!!.is_exp == "0") "无经验" else "有经验"} - ${settledInfo!!.service_year}年${if (settledInfo!!.is_pay_team_money == 0) "" else "/${settledInfo!!.join_money}元"}"
        }

    }

}